package com.example.studentknowledge.repository;

import com.example.studentknowledge.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 用户Repository接口
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    /**
     * 根据用户名查找用户
     */
    Optional<User> findByUsername(String username);
    
    /**
     * 根据邮箱查找用户
     */
    Optional<User> findByEmail(String email);
    
    /**
     * 检查用户名是否存在
     */
    boolean existsByUsername(String username);
    
    /**
     * 检查邮箱是否存在
     */
    boolean existsByEmail(String email);
    
    /**
     * 根据角色查找用户
     */
    List<User> findByRole(User.Role role);
    
    /**
     * 根据启用状态查找用户
     */
    Page<User> findByEnabled(Boolean enabled, Pageable pageable);
    
    /**
     * 根据角色和启用状态查找用户
     */
    Page<User> findByRoleAndEnabled(User.Role role, Boolean enabled, Pageable pageable);
    
    /**
     * 根据用户名或真实姓名模糊查询
     */
    @Query("SELECT u FROM User u WHERE u.username LIKE %:keyword% OR u.realName LIKE %:keyword%")
    Page<User> findByUsernameContainingOrRealNameContaining(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 获取积分排行榜
     */
    @Query("SELECT u FROM User u WHERE u.enabled = true ORDER BY u.points DESC")
    List<User> findTopUsersByPoints(Pageable pageable);
    
    /**
     * 根据积分范围查找用户
     */
    @Query("SELECT u FROM User u WHERE u.points BETWEEN :minPoints AND :maxPoints ORDER BY u.points DESC")
    List<User> findByPointsBetween(@Param("minPoints") Integer minPoints, @Param("maxPoints") Integer maxPoints);
    
    /**
     * 统计用户总数
     */
    @Query("SELECT COUNT(u) FROM User u WHERE u.enabled = true")
    Long countActiveUsers();
    
    /**
     * 根据角色统计用户数量
     */
    @Query("SELECT COUNT(u) FROM User u WHERE u.role = :role AND u.enabled = true")
    Long countByRoleAndEnabled(@Param("role") User.Role role);
}